package com.it.sun.esaychat.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.sun.easychat.model.constant.HttpResponseMsg;
import com.it.sun.easychat.model.exception.ApplicationException;
import com.it.sun.easychat.model.vo.UserPasswordVO;
import com.it.sun.esaychat.user.entity.UserEntity;
import com.it.sun.esaychat.user.mapper.UserMapper;
import com.it.sun.esaychat.user.service.IUserServices;
import com.it.sun.esaychat.user.vo.User;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sunmannian
 * @since 2020-05-24
 */
@Service
public class UserServices extends ServiceImpl<UserMapper, UserEntity> implements IUserServices {

    private PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    @Override
    public void insert(UserEntity user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        this.save(user);
    }

    @Override
    public void changePassword(UserPasswordVO userPasswordVO) {
        UserEntity user = getUserByUsername(userPasswordVO.getUsername());
        if (!passwordEncoder.matches(userPasswordVO.getOriginalPassword(),
                user.getPassword())) {
            throw new ApplicationException(HttpResponseMsg.USERNAME_OR_PASSWORD_ERROR);
        }
        user.setPassword(passwordEncoder.encode(userPasswordVO.getPassword()));
        updateById(user);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws
            UsernameNotFoundException {
        UserEntity one = getUserByUsername(username);
        User user = User.builder().build();
        BeanUtils.copyProperties(one, user);
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("hi"));
        user.setCredentialsNonExpired(true);
        user.setAccountNonExpired(true);
        user.setAccountNonLocked(true);
        user.setEnabled(true);
        return user;
    }

    private UserEntity getUserByUsername(String username) {
        UserEntity user = this.getOne(Wrappers.lambdaQuery(UserEntity.class).
                eq(UserEntity::getUsername, username));
        if (null == user) {
            throw new UsernameNotFoundException("未找到用户名");
        }
        return user;
    }

}
